<?php
set_include_path('system'.PATH_SEPARATOR.'templates');

require_once('Template.php');
require_once('RedirectBrowserException.php');
require_once('DatabaseUtility.php');
require_once('CustomFunctions.php');

$tmpl = new Template();

$id = $_GET['id'];
$ref = $_GET['ref'];

openDatabase();
$query='SELECT annotation,symbol,sequence,latin,commonName FROM protein,organism WHERE protein.id = \''.$id.'\' AND protein.organism=organism.label;';
$rows = runQuery($query);

// query database for phosphorylation sites in this protein
$query  = "SELECT id, locationInProtein FROM site WHERE protein = $id AND ptm='p'";
if (!empty($ref)) {
	$query .= " AND EXISTS (SELECT * FROM mass,peptide,peptideSiteRelation WHERE mass.dataSource=$ref AND mass.id=peptide.mass AND peptideSiteRelation.peptide=peptide.id AND peptideSiteRelation.site=site.id)";
}
$rows2 = runQuery($query);
$sites = array();
foreach($rows2 as $row) {
	$sites[$row['locationInProtein']] = $row['id'];
}
ksort($sites);

// query dataSource
$query = "SELECT id,reference FROM dataSource,proteinDataSourceRelation WHERE protein='$id' AND dataSource=id ORDER BY pubmed DESC";
$rows3 = runQuery($query);
foreach($rows3 as $row) {
	$dataSource[$row['id']] = $row['reference'];
}
if (count($dataSource)>1) {
	$dataSource[0] = "All";
	ksort($dataSource);
}

// reference links
$refLink = '';
$refs = array();
$query ="SELECT id,link,reference FROM dataSource ORDER BY pubmed DESC;";
$result = runQuery($query);
foreach($result as $row) {
	$refID = $row['id'];
	$link = $row['link'];
	if (empty($link)) {
			$refs[$refID] = $row['reference'];
	} else {
			$refs[$refID] = $link;
	}
}
if(!empty($ref)) $refLink = $refs[$ref];
else if (count($dataSource) == 1) {
	$refID = array_keys($dataSource);
	$refLink = $refs[$refID[0]];
}

$mass = spectralOfProtein($id, $ref);

$tmpl->id 			= $id;
$tmpl->ref			= $ref;
$tmpl->refLink		= $refLink;
$tmpl->sites 		= $sites;
$tmpl->dataSource 	= $dataSource;
$tmpl->accessions 	= getXrefLink($id);
$tmpl->description 	= $rows[0]['annotation'];
$tmpl->organism 	= '<i>'.$rows[0]['latin'].'</i> ('.$rows[0]['commonName'].')';
$tmpl->numSites 	= count($sites);
$tmpl->numSpectra 	= count($mass);
$tmpl->sequence 	= $rows[0]['sequence'];
closeDatabase();

$tmpl->current = 'browse';
$tmpl->pageContent = $tmpl->build('protein.tmpl');

print $tmpl->build('page.tmpl');
?>